package com.jet.core.utils;

import cn.hutool.core.util.StrUtil;

import java.math.BigDecimal;
import java.math.RoundingMode;

public class AmountUtil {

    public static final Long BASE_UNIT = 100L;
    public static final int BASE_SCALE = 2;
    public static final RoundingMode ROUNDING_MODE = RoundingMode.DOWN;

    public static long parse(BigDecimal amount) {
        if (amount == null) {
            return 0;
        }
        return amount.multiply(BigDecimal.valueOf(BASE_UNIT)).longValue();
    }

    public static long parse(String amount) {
        if (StrUtil.isBlank(amount)) {
            return 0;
        }
        return parse(parseBigDecimal(amount));
    }

    public static BigDecimal parseBigDecimal(long amount) {
        return parseBigDecimal(amount, BASE_SCALE);
    }

    public static BigDecimal parseBigDecimal(long amount, int scale) {
        return BigDecimal.valueOf(amount).divide(BigDecimal.valueOf(BASE_UNIT), scale, ROUNDING_MODE);
    }

    public static BigDecimal format(BigDecimal amount) {
        return format(amount, BASE_SCALE);
    }

    public static BigDecimal format(BigDecimal amount, int scale) {
        return amount.setScale(scale, ROUNDING_MODE);
    }

    public static String parseYuan(long amount) {
        return parseYuan(amount, BASE_SCALE);
    }

    public static String parseYuan(long amount, int scale) {
        return BigDecimal.valueOf(amount).divide(BigDecimal.valueOf(BASE_UNIT), scale, ROUNDING_MODE).toPlainString();
    }

    public static BigDecimal parseBigDecimal(String amount) {
        if (StrUtil.isBlank(amount)) {
            return BigDecimal.ZERO;
        }
        return BigDecimal.valueOf(Double.parseDouble(amount)).multiply(BigDecimal.valueOf(BASE_SCALE));
    }

    /**
     * 乘法，保留两位小数
     *
     * @param startAmount
     * @param endAmount
     * @return
     */
    public static BigDecimal multiply(BigDecimal startAmount, BigDecimal endAmount) {
        if (startAmount == null || endAmount == null) {
            return BigDecimal.ZERO;
        }
        return startAmount.multiply(endAmount).setScale(BASE_SCALE, ROUNDING_MODE);
    }

    /**
     * 除法，保留两位小数
     *
     * @param startAmount
     * @param endAmount
     * @return
     */
    public static BigDecimal divide(BigDecimal startAmount, BigDecimal endAmount) {
        if (startAmount == null || endAmount == null || endAmount.equals(BigDecimal.ZERO)) {
            return BigDecimal.ZERO;
        }
        return startAmount.divide(endAmount, BASE_SCALE, ROUNDING_MODE);
    }
}
